package chpt09;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

class CalcCallableTask implements Callable<Integer> {
	private int n;

	public CalcCallableTask(int n) {
		this.n = n;
	}

	@Override
	public Integer call() throws Exception {
		Random rnd = new Random();
		int sum = 0;
		for (int i = 1; i < n + 1; i++) {
			sum += i;
		}
		int sleeTime = rnd.nextInt(10);
		TimeUnit.SECONDS.sleep(sleeTime);
		String name = Thread.currentThread().getName();
		System.out.printf("%s 计算的结果为 %d! " + 
				"共花费 %d 秒时间%n", name, sum, sleeTime);
		return sum;
	}

}

public class ThreadPoolTest {
	public static void main(String[] args) {
		ExecutorService pool = Executors.newCachedThreadPool();
		int begin = 10, end = 15;
		List<Future<Integer>> results = new ArrayList<>();
		for (int i = begin; i < end; i++) {
			results.add(pool.submit(new CalcCallableTask(i)));
		}
		System.out.println("---计算结果---");
		for (Future<Integer> e : results) {
			try {
				System.out.println(e.get());
			} catch (InterruptedException | ExecutionException e1) {
				e1.printStackTrace();
			}
		}
		pool.shutdown();
	}

}
